import re
import time
import requests

from common import settings

session = requests.Session()

# session.cookies.update({'sessionid', 'v2m629a5e5e63id8fuqs3g1sflofwofy'})
session.headers = {'user-agent': 'yuanrenxue.project'}
session.cookies.update({"sessionid": "v2m629a5e5e63id8fuqs3g1sflofwofy"})  # 更新sessionid


def extract_yuanrenxue_cookie(text):
    session2 = ''.join(re.findall('\'(.*?)\'', text)[:-1])
    return session2.replace('yuanrenxue_cookie=', '')


def fetch_0() -> None:
    response = session.get('https://match.yuanrenxue.cn/match/13', proxies=settings.proxies)
    # print(session.cookies)
    # print(session.cookies.get('sessionid'))
    """
    for key, value in response.cookies.items():
        print(f"Key: {key}, Value: {value}")
    """
    text = response.text
    yuanrenxue_cookie = extract_yuanrenxue_cookie(text)
    cookie = {
        # 'sessionid': 'v2m629a5e5e63id8fuqs3g1sflofwofy',
        'yuanrenxue_cookie': yuanrenxue_cookie
    }
    print(cookie)
    session.cookies.update(cookie)
    return cookie


def fetch(page: int) -> list[int]:
    params = None
    if page > 1:
        params = {
            'page': page,
        }
    response = session.get('https://match.yuanrenxue.cn/api/match/13', params=params
                           # , headers=headers,
                           , proxies=settings.proxies)
    print(response.text)
    if response.status_code != 200:
        exit(500)
    return [x['value'] for x in response.json()['data']]


def main():
    values = []
    fetch_0()
    time.sleep(1)
    for page in range(1, 6):
        time.sleep(0.1)
        values.extend(fetch(page))
    print(sum(values))


# 任务十三：还是抓取这5页的数字，计算加和并提交结果
if __name__ == '__main__':
    main()
